package com.quanyan.travel.component.task;

import com.alibaba.fastjson.JSON;
import com.github.ltsopensource.core.domain.Action;
import com.github.ltsopensource.core.domain.Job;
import com.github.ltsopensource.tasktracker.Result;
import com.github.ltsopensource.tasktracker.runner.JobContext;
import com.github.ltsopensource.tasktracker.runner.JobRunner;
import com.quanyan.travel.constants.OutdoorConstants;
import com.quanyan.travel.service.TravelAdminService;
import com.quanyan.travel.service.TravelOrderService;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by yue.yuan on 2016/8/4.
 */
@Component
public class TravelTaskJob implements JobRunner{

    private static Logger logger = Logger.getLogger(TravelTaskJob.class);

    @Autowired
    private TravelOrderService travelOrderService;

    @Autowired
    private TravelAdminService travelAdminService;


    @Override
    public Result run(JobContext jobContext) throws Throwable {
        Job job = jobContext.getJob();
        if (job == null) {
            return new Result(Action.EXECUTE_EXCEPTION, "任务不存在");
        }
        logger.info("收到定时任务：" + JSON.toJSONString(job));
        String taskId = job.getTaskId();
        try {
            if (taskId.contains(OutdoorConstants.TRAVEL_JOB_ID_CLOSE_ORDER_START_NOTIFY)) {
                travelOrderService.refreshTravelStorage();
                return new Result(Action.EXECUTE_SUCCESS, "--回收不合法订单---task-execute-success----");
            } else if (taskId.contains(OutdoorConstants.TRAVEL_JOB_ID_UPDATE_ACTIVITY_START_NOTIFY)) {
                travelAdminService.refreshTravelActivityStatus();
                return new Result(Action.EXECUTE_SUCCESS, "--清除过期活动---task-execute-success----");
            } else if (taskId.contains(OutdoorConstants.TRAVEL_JOB_ID_UPDATE_PRICE_START_NOTIFY)) {
                travelAdminService.updateLowPrice();
                return new Result(Action.EXECUTE_SUCCESS, "--更新最低价格和开始时间---task-execute-success----");
            }else if (taskId.contains(OutdoorConstants.TRAVEL_JOB_ID_REMIND_PAY_START_NOTIFY)) {
                travelAdminService.remindUserPay();
                return new Result(Action.EXECUTE_SUCCESS, "--支付提醒---task-execute-success----");
            }else {
                //没有匹配类型，默认提交成功
                return new Result(Action.EXECUTE_SUCCESS, "当前没有可执行的业务逻辑");
            }
        } catch (Exception e) {
            logger.info("Run job failed!", e);
            return new Result(Action.EXECUTE_LATER, "--task-execute-fail---"+e);
        }
    }
}
